package com.atguigu.flink.state;

import com.atguigu.flink.function.MyUtil;
import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2022/12/17
 * 
        去重： 每种传感器重复的水位值

        Map：  key使用set存放，可以去重。
 */
public class Demo7_MapState
{
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {

                       private MapState<Integer, String> vc;

                       @Override
                       public void open(Configuration parameters) throws Exception {
                           vc = getRuntimeContext().getMapState(new MapStateDescriptor<Integer, String>("vc", Integer.class, String.class));
                       }


                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                          //作为Key放入状态
                           vc.put(value.getVc(),"");

                           //获取去重后的key
                           out.collect(ctx.getCurrentKey() + ":"+ MyUtil.parseIterable(vc.keys()));

                       }
                   })
                   .print();
        
                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
        
    }
}
